Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

6-Me-in-U #20

Merged
merged 4 commits into from
Jul 14, 2024
Merged

6-Me-in-U #20

merged 4 commits into from
Jul 14, 2024

Conversation

Me-in-U
Copy link
Collaborator

@Me-in-U Me-in-U commented May 19, 2024

πŸ”— 문제 링크

2252번 쀄 μ„Έμš°κΈ°

βœ”οΈ μ†Œμš”λœ μ‹œκ°„

1μ‹œκ°„

✨ μˆ˜λ„ μ½”λ“œ

μœ„μƒ μ •λ ¬(topological sorting)은 유ν–₯ κ·Έλž˜ν”„μ˜ 꼭짓점듀(vertex)을 λ³€μ˜ λ°©ν–₯을 거슀λ₯΄μ§€ μ•Šλ„λ‘ λ‚˜μ—΄ν•˜λŠ” 것을 μ˜λ―Έν•œλ‹€.

μ˜ˆμ‹œ) λ§Œμ•½ νŠΉμ • μˆ˜κ°•κ³Όλͺ©μ— μ„ μˆ˜κ³Όλͺ©μ΄ μžˆλ‹€λ©΄ κ·Έ μ„ μˆ˜ κ³Όλͺ©λΆ€ν„° μˆ˜κ°•ν•΄μ•Ό ν•˜λ―€λ‘œ, νŠΉμ • κ³Όλͺ©λ“€μ„ μˆ˜κ°•ν•΄μ•Ό ν•  λ•Œ μœ„μƒ 정렬을 톡해 μ˜¬λ°”λ₯Έ μˆ˜κ°• μˆœμ„œλ₯Ό μ°Ύμ•„λ‚Ό 수 μžˆλ‹€.

1.

Input: G = (V, E)

  1. inDegreeκ°€ 0인 vertexλ₯Ό 큐에 μΆ”κ°€ν•œλ‹€.
  2. 큐가 λΉ„μ–΄μžˆμ§€ μ•ŠμœΌλ©΄ μ•„λž˜ 반볡
  3. νμ—μ„œ 정점 xλ₯Ό κΊΌλ‚Έλ‹€
  4. 정점 x와 μ—°κ²°λœ μ •μ μ˜ 차수λ₯Ό 1 λ‚΄λ¦°λ‹€.
  5. 쀄어든 μ°¨μˆ˜κ°€ 1일 경우 ν•΄λ‹Ή 정점을 큐에 μΆ”κ°€ν•œλ‹€.
public static String topologySort(int N) {
    StringBuilder sb = new StringBuilder();
    Queue<Integer> queue = new LinkedList<>();
    for (int i = 1; i < N + 1; i++) {
        if (inDegree[i] == 0) {
            queue.add(i);
        }
    }
    while (!queue.isEmpty()) {
        int now = queue.poll();
        sb.append(now).append(' ');
        for (int next : graph[now]) {
            if (--inDegree[next] == 0) {
                queue.add(next);
            }
        }
    }
    return sb.toString();
}

μŠ€ν¬λ¦°μƒ· 2024-05-19 222339
초기 μƒνƒœ

κ·Έλž˜ν”„ G
1 -> 3
2 -> 3
3 ->

inDegree[]
{0,0,2}

큐에 μ°¨μˆ˜κ°€ 0인 정점 μΆ”κ°€

  1. 반볡 Queue(1,2)
    {
    νμ—μ„œ 1을 κΊΌλ‚΄κ³  "1" 좜λ ₯
    1κ³Ό μ—°κ²°λœ 정점 3의 차수λ₯Ό 1κ°μ†Œ => inDegree[]{0,0,1}
    }

  2. 반볡 Queue(2)
    {
    νμ—μ„œ 2을 κΊΌλ‚΄κ³  "2" 좜λ ₯
    2와 μ—°κ²°λœ 정점 3의 차수λ₯Ό 1κ°μ†Œ => inDegree[]{0,0,0}
    쀄어든 μ°¨μˆ˜κ°€ 0이 λ˜μ—ˆμŒμœΌλ‘œ 큐에 0μΆ”κ°€
    }

  3. 반볡 Queue(3)
    {
    νμ—μ„œ 3을 κΊΌλ‚΄κ³  "3" 좜λ ₯
    }

μ’…λ£Œ.

좜λ ₯ κ²°κ³Ό 1,2,3

큐에 λ„£λŠ” μˆœμ„œμ— λ”°λΌμ„œ 2,1,3이 될 μˆ˜λ„ μžˆλ‹€.
λ¬Όλ‘  이것도 정닡이닀.

Copy link
Contributor

@9kyo-hwang 9kyo-hwang left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

μœ„μƒ 정렬은 DFSλ₯Ό μ΄μš©ν•΄μ„œλ„ μˆ˜ν–‰ν•  수 있죠. λ³„λ„λ‘œ μ§„μž…μ°¨μˆ˜λ₯Ό 기둝할 ν•„μš” 없이, 기본적인 DFS μˆ˜ν–‰ν•˜λ“― ν•˜λ˜ ν•¨μˆ˜ λ§ˆμ§€λ§‰μ— λ°©λ¬Έν•œ λ…Έλ“œλ₯Ό λ„£λŠ” μ‹μ˜ λ³€ν˜•λ§Œ μ£Όλ©΄ 되기 λ•Œλ¬Έμ— μ½”λ“œκ°€ BFS 방식에 λΉ„ν•΄ μ‹¬ν”Œν•˜λ‹€κ³  μƒκ°λ˜λ„€μš” :)

import java.io.*;
import java.util.*;

public class Main {
    static int N, M;
    static List<Integer>[] adjacencyList;
    static List<Integer> orderOfVisit;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        StringTokenizer st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());
        
        adjacencyList = new ArrayList[N + 1];
        for (int i = 0; i <= N; i++) {
            adjacencyList[i] = new ArrayList<>();
        }
        
        for (int i = 0; i < M; i++) {
            st = new StringTokenizer(br.readLine());
            int A = Integer.parseInt(st.nextToken());
            int B = Integer.parseInt(st.nextToken());
            adjacencyList[A].add(B);
        }
        
        topologySort();
        
        Collections.reverse(orderOfVisit);
        for (int node : orderOfVisit) {
            bw.write(node + " ");
        }
        bw.flush();
        bw.close();
        br.close();
    }

    static void DFS(boolean[] visited, int srcNode) {
        visited[srcNode] = true;
        for (int dstNode : adjacencyList[srcNode]) {
            if (!visited[dstNode]) {
                DFS(visited, dstNode);
            }
        }
        orderOfVisit.add(srcNode);
    }

    static void topologySort() {
        boolean[] visited = new boolean[N + 1];
        orderOfVisit = new ArrayList<>();
        for (int node = 1; node <= N; node++) {
            if (!visited[node]) {
                DFS(visited, node);
            }
        }
    }
}

Copy link
Collaborator

@wjdheesp44 wjdheesp44 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

import sys
from collections import deque

input = sys.stdin.readline
N, M = map(int, input().split())

in_degree = [0]*(N+1)
graph = [[] for _ in range(N+1)]
q = deque()
answer = []

for i in range(M):
    a, b = map(int, input().split())
    graph[a].append(b)
    in_degree[b] += 1

for i in range(1, N+1):
    if in_degree[i] == 0:
        q.append(i)

while q:
    tmp = q.popleft()
    answer.append(tmp)
    for i in graph[tmp]:
        in_degree[i] -= 1
        if in_degree[i] == 0:
            q.append(i)

for i in answer:
    print(i, end=' ')

μœ„μƒμ •λ ¬μ— λŒ€ν•΄ 처음 μ•Œκ²Œ λ˜μ—ˆλ„€μš”. μ €λŠ” bfs둜 ν’€μ–΄λ΄€μŠ΅λ‹ˆλ‹€. κ³ μƒν•˜μ…¨μŠ΅λ‹ˆλ‹€!

Copy link
Collaborator

@erase-jeong erase-jeong left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

μ΄λ²ˆκΈ°νšŒμ— μœ„μƒμ •λ ¬μ— λŒ€ν•΄μ„œ μ•Œκ²Œλ˜κ³  κ³΅λΆ€ν•΄λ³΄κ²Œ λ˜μ—ˆλ„€μš”!

μˆ˜κ³ ν•˜μ…¨μŠ΅λ‹ˆλ‹€~

from collections import deque


def sort(N,comparisons):
    graph=[[] for _ in range(N+1)] 
    in_degree=[0]*(N+1)  

    for A,B in comparisons:
        graph[A].append(B)
        in_degree[B]+=1


    queue=deque()
    for i in range(1,N+1):
        if in_degree[i]==0:
            queue.append(i)

    
    result=[]
    while queue:
        current=queue.popleft()
        result.append(current)
        for neighbor in graph[current]:
            in_degree[neighbor]-=1
            if in_degree[neighbor]==0:
                queue.append(neighbor)


    return result

    
N,M=map(int,input().split())

comparisons=[] 
for _ in range(M): 
    a,b=map(int,input().split()) 
    comparisons.append((a,b)) 


sorted_students=sort(N,comparisons)

print(' '.join(map(str,sorted_students)))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants